package com.guomei.service.exam.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guomei.bean.exam.domain.ExamAnswerDetail;
import com.guomei.bean.exam.domain.ExamQuestion;
import com.guomei.bean.exam.domain.ExamUserAnswerVO;
import com.guomei.mapper.curse.ExamAnswerDetailMapper;
import com.guomei.mapper.curse.ExamQuestionMapper;
import com.guomei.service.exam.ExamAnswerDetailService;
import com.guomei.utils.PageData;
import com.guomei.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 考试答卷详情服务实现类
 */
@Service
@Slf4j
@Transactional
public class ExamAnswerDetailServiceImpl implements ExamAnswerDetailService {
    
    @Resource
    private ExamAnswerDetailMapper examAnswerDetailMapper;

    @Resource
    private ExamQuestionMapper examQuestionMapper;

    @Override
    public ExamAnswerDetail getById(Long id) {
        if (id == null) {
            return null;
        }
        return examAnswerDetailMapper.selectById(id);
    }

    @Override
    public List<ExamAnswerDetail> getAll() {
        return examAnswerDetailMapper.selectAll();
    }

    @Override
    public Result<?> getByCondition(ExamAnswerDetail examAnswerDetail) {
        PageHelper.startPage(examAnswerDetail.getPageNum(), examAnswerDetail.getPageSize());
        List<ExamAnswerDetail> examAnswerDetails = examAnswerDetailMapper.selectByCondition(examAnswerDetail);
        if (examAnswerDetails != null && !examAnswerDetails.isEmpty()){
            for (ExamAnswerDetail answerDetail : examAnswerDetails) {
                ExamQuestion examQuestion = examQuestionMapper.selectById(answerDetail.getQuestionId());
                answerDetail.setExamQuestion(examQuestion);
            }
        }
        // 封装分页结果到PageData
        PageData<ExamAnswerDetail> pageData = new PageData<>();
        PageInfo<ExamAnswerDetail> pageInfo = new PageInfo<>(examAnswerDetails);
        pageData.setTotal(pageInfo.getTotal());
        pageData.setData(pageInfo.getList());
        pageData.setPageNum(examAnswerDetail.getPageNum());
        pageData.setPageSize(examAnswerDetail.getPageSize());
        return Result.success(pageData);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(ExamAnswerDetail examAnswerDetail) {
        if (examAnswerDetail == null) {
            return false;
        }

        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        examAnswerDetail.setCreatedTime(now);
        examAnswerDetail.setUpdatedTime(now);

        return examAnswerDetailMapper.insert(examAnswerDetail) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchSave(List<ExamAnswerDetail> examAnswerDetails) {
        if (examAnswerDetails == null || examAnswerDetails.isEmpty()) {
            return false;
        }

        LocalDateTime now = LocalDateTime.now();
        for (ExamAnswerDetail examAnswerDetail : examAnswerDetails) {
            // 设置创建和更新时间
            examAnswerDetail.setCreatedTime(now);
            examAnswerDetail.setUpdatedTime(now);
        }

        return examAnswerDetailMapper.batchInsert(examAnswerDetails) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(ExamAnswerDetail examAnswerDetail) {
        if (examAnswerDetail == null || examAnswerDetail.getId() == null) {
            return false;
        }
        
        // 设置更新时间
        examAnswerDetail.setUpdatedTime(LocalDateTime.now());
        
        return examAnswerDetailMapper.updateById(examAnswerDetail) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeById(Long id) {
        if (id == null) {
            return false;
        }
        return examAnswerDetailMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchRemove(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        return examAnswerDetailMapper.batchDelete(ids) > 0;
    }

    @Override
    public List<ExamAnswerDetail> getByAnswerId(Long answerId) {
        if (answerId == null) {
            return null;
        }
        return examAnswerDetailMapper.selectByAnswerId(answerId);
    }

    @Override
    public List<ExamAnswerDetail> getByQuestionId(Long questionId) {
        if (questionId == null) {
            return null;
        }
        return examAnswerDetailMapper.selectByQuestionId(questionId);
    }

    @Override
    public ExamAnswerDetail getByAnswerIdAndQuestionId(Long answerId, Long questionId) {
        if (answerId == null || questionId == null) {
            return null;
        }
        return examAnswerDetailMapper.selectByAnswerIdAndQuestionId(answerId, questionId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByAnswerId(Long answerId) {
        if (answerId == null) {
            return false;
        }
        return examAnswerDetailMapper.deleteByAnswerId(answerId) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByQuestionId(Long questionId) {
        if (questionId == null) {
            return false;
        }
        return examAnswerDetailMapper.deleteByQuestionId(questionId) > 0;
    }

    @Override
    public int countByAnswerId(Long answerId) {
        if (answerId == null) {
            return 0;
        }
        return examAnswerDetailMapper.countByAnswerId(answerId);
    }

    @Override
    public int countByQuestionId(Long questionId) {
        if (questionId == null) {
            return 0;
        }
        return examAnswerDetailMapper.countByQuestionId(questionId);
    }

    @Override
    public Integer sumScoreByAnswerId(Long answerId) {
        if (answerId == null) {
            return 0;
        }
        return examAnswerDetailMapper.sumScoreByAnswerId(answerId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> saveAnswer(Long answerId, Long questionId, String userAnswer) {
        try {
            // 1. 验证参数
            if (answerId == null || questionId == null) {
                return Result.fail("参数不能为空");
            }

            // 2. 检查是否已存在答题记录
            ExamAnswerDetail existingDetail = getByAnswerIdAndQuestionId(answerId, questionId);
            if (existingDetail != null) {
                // 更新现有记录
                existingDetail.setUserAnswer(userAnswer);
                existingDetail.setUpdatedTime(LocalDateTime.now());
                boolean success = update(existingDetail);
                if (success) {
                    return Result.success("答题记录更新成功");
                } else {
                    return Result.fail("答题记录更新失败");
                }
            } else {
                // 创建新记录
                ExamAnswerDetail examAnswerDetail = new ExamAnswerDetail();
                examAnswerDetail.setAnswerId(answerId);
                examAnswerDetail.setQuestionId(questionId);
                examAnswerDetail.setUserAnswer(userAnswer);

                boolean success = save(examAnswerDetail);
                if (success) {
                    return Result.success("答题记录保存成功");
                } else {
                    return Result.fail("答题记录保存失败");
                }
            }

        } catch (Exception e) {
            log.error("保存答题记录失败", e);
            return Result.fail("保存答题记录失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> batchSaveAnswer(Long answerId, List<ExamAnswerDetail> answerDetails) {
        try {
            // 1. 验证参数
            if (answerId == null || answerDetails == null || answerDetails.isEmpty()) {
                return Result.fail("参数不能为空");
            }

            // 2. 设置答卷ID
            for (ExamAnswerDetail detail : answerDetails) {
                detail.setAnswerId(answerId);
            }

            // 3. 批量保存
            boolean success = batchSave(answerDetails);
            if (success) {
                return Result.success("批量保存答题记录成功");
            } else {
                return Result.fail("批量保存答题记录失败");
            }

        } catch (Exception e) {
            log.error("批量保存答题记录失败", e);
            return Result.fail("批量保存答题记录失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> scoreAnswer(Long answerDetailId, Integer score, String reviewRemark) {
        try {
            // 1. 验证参数
            if (answerDetailId == null || score == null) {
                return Result.fail("参数不能为空");
            }

            // 2. 检查答题记录
            ExamAnswerDetail examAnswerDetail = getById(answerDetailId);
            if (examAnswerDetail == null) {
                return Result.fail("答题记录不存在");
            }

            // 3. 更新分数和备注
            examAnswerDetail.setScore(score);
            examAnswerDetail.setReviewRemark(reviewRemark);
            examAnswerDetail.setUpdatedTime(LocalDateTime.now());

            boolean success = update(examAnswerDetail);
            if (success) {
                return Result.success("评分成功");
            } else {
                return Result.fail("评分失败");
            }

        } catch (Exception e) {
            log.error("评分失败", e);
            return Result.fail("评分失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<?> batchScoreAnswer(List<ExamAnswerDetail> answerDetails) {
        try {
            // 1. 验证参数
            if (answerDetails == null || answerDetails.isEmpty()) {
                return Result.fail("参数不能为空");
            }

            // 2. 批量更新
            for (ExamAnswerDetail detail : answerDetails) {
                if (detail.getId() != null) {
                    detail.setUpdatedTime(LocalDateTime.now());
                    update(detail);
                }
            }

            return Result.success("批量评分成功");

        } catch (Exception e) {
            log.error("批量评分失败", e);
            return Result.fail("批量评分失败：" + e.getMessage());
        }
    }

    @Override
    public List<ExamUserAnswerVO> getUserAnswersByAnswerId(Long answerId) {
        if (answerId == null) {
            return java.util.Collections.emptyList();
        }
        return examAnswerDetailMapper.selectUserAnswersByAnswerId(answerId);
    }

    @Override
    public List<ExamUserAnswerVO> getUserAnswersByExamIdAndUserId(Long examId, Long userId) {
        if (examId == null || userId == null) {
            return java.util.Collections.emptyList();
        }
        return examAnswerDetailMapper.selectUserAnswersByExamIdAndUserId(examId, userId);
    }
}
